//
//  DHDCViewController.m
//  发;fjag
//
//  Created by 刘鹏飞 on 2016/11/15.
//  Copyright © 2016年 刘鹏飞. All rights reserved.
//

#import "DHDCViewController.h"
#import "NetworkTool.h"
#import <SVProgressHUD.h>
#import <MJRefresh.h>
#import <Masonry.h>

#define delay(time) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((time) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{[SVProgressHUD dismiss];})

#define delaysuc(time) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((time) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{[SVProgressHUD showSuccessWithStatus:@"加载成功!"];})

#define delayUpdata(time) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((time) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{[self.tabelView.mj_header endRefreshing];[self.tabelView.mj_footer endRefreshing];})

@interface DHDCViewController () <UITableViewDelegate,UITableViewDataSource>

/*---tabel---*/
@property (nonatomic,weak)UITableView *tabelView;

/*---btn数组---*/
@property (nonatomic,strong)NSMutableArray *btnArr;

/*---选择的数据数组---*/
@property (nonatomic,strong)NSMutableArray *cellArr;


@end

@implementation DHDCViewController

static int i  = 1;
static int j  = 1;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.btnArr = [NSMutableArray array];
    self.cellArr = [NSMutableArray array];
    if (self.tag == 1) {
        self.listArr = [NSMutableArray array];
        [self requestWithURLStr:@"http://iosapi.itcast.cn/doctor/searchCI3List.json.php" parameters:@{@"page":@1,@"page_size":@15,@"ci1_id":self.ID,@"keyword":@""}];
    }
    
}

#pragma mark - 网络请求

/**
 网络请求
 */
-(void)requestWithURLStr:(NSString *)URL parameters:(NSDictionary *)parameters  {
    [[NetworkTool sharedTool] POSTWithURLStr:URL parameters:parameters success:^(id responseObject) {
        if (responseObject != nil) {
            //调用第三方弹出提示框
            [SVProgressHUD showWithStatus:@"正在加载中...."];
            [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
            delaysuc(1.0);
            delay(2.0);
            //结束刷新
            delayUpdata(2.0);
            [self.listArr addObjectsFromArray:responseObject[@"data"]];
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                
                [self.tabelView reloadData];
            }];
        }
    } failed:^(NSError *error) {
        //调用第三方弹出提示框
        [SVProgressHUD showWithStatus:@"您的网络不给力,加载失败!"];
        [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
        delay(1.0);
        [self.tabelView.mj_header endRefreshing];
        
    }];
}



#pragma mark - 实现数据源方法

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.tag == 2) {
        return self.modelArr.count;
    }
    return self.listArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (self.tag == 0) {
        cell.textLabel.text = self.listArr[indexPath.row];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    if (self.tag == 1) {
        NSDictionary *dict = self.listArr[indexPath.row];
        cell.textLabel.text = dict[@"ci3_name"];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    if (self.tag == 2 ) {
        UIButton *btn = [[UIButton alloc] init];
        [self.btnArr addObject:btn];
        [cell.contentView addSubview:btn];
        [btn setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:@"imageSelected"] forState:UIControlStateSelected];
        DHDiseaseClassModel *model = self.modelArr[indexPath.row];
        btn.selected = model.isClick;
        cell.textLabel.text = model.diseaseClass;
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(cell.contentView);
            make.right.equalTo(cell.mas_right).offset(-8);
            make.size.mas_equalTo(CGSizeMake(30, 30));
        }];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(sureAtion:)];
    }
    
    return cell;
}

//确定按钮事件
-(void)sureAtion:(UIBarButtonItem *)sender {
    for (DHDiseaseClassModel *model in self.modelArr) {
        if (model.isClick == YES) {
            [self.cellArr addObject:model];
        }
    }
    self.myTapBlock(self.cellArr,self.modelArr);
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

#pragma mark - 实现代理方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    
    if (self.myBlock != nil && self.tag == 0) {
        NSString *str = self.listArr[indexPath.row];
        self.myBlock(str,indexPath.row);
        [self.navigationController popViewControllerAnimated:YES];
    }else if (self.myBlock != nil && self.tag == 1){
        NSDictionary *dict = self.listArr[indexPath.row];
        NSString *str = dict[@"ci3_name"];
        self.myBlock(str,indexPath.row);
        [self.navigationController popViewControllerAnimated:YES];
    }else {
        UIButton *btn = self.btnArr[indexPath.row];
        DHDiseaseClassModel *model = self.modelArr[indexPath.row];
        btn.selected = !btn.selected;
        model.isClick = !model.isClick;
    }
}


#pragma mark - 创建子控件,设置上下拉刷新
-(void)xhhSetupSubviews {
    
    //创建子控件
    UITableView *tabelView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    [self.view addSubview:tabelView];
    self.tabelView = tabelView;
    
    //注册cell
    [tabelView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    
    //设置属性
    tabelView.showsVerticalScrollIndicator = NO;
    
    //设置代理
    tabelView.dataSource = self;
    tabelView.delegate = self;
    
    //设置下拉刷新
    if (self.tag == 1) {
        MJRefreshStateHeader *header = [MJRefreshStateHeader headerWithRefreshingBlock:^{
            NSNumber *num = [NSNumber numberWithInt:j++];
            if (j>1) {
                [SVProgressHUD showSuccessWithStatus:@"已经是最新数据了"];
                [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
                delay(1.0);
                delayUpdata(1.0);
                return;
            }
            [self requestWithURLStr:@"http://iosapi.itcast.cn/doctor/searchCI3List.json.php" parameters:@{@"page":num,@"page_size":@15,@"ci1_id":self.ID,@"keyword":@""}];
        }];
        header.lastUpdatedTimeLabel.hidden = YES;
        
        self.tabelView.mj_header = header;
        //设置上拉刷新
        MJRefreshAutoStateFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            NSNumber *num = [NSNumber numberWithInt:++i];
            if (i>self.num) {
                [SVProgressHUD showSuccessWithStatus:@"没有数据了"];
                [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeNone];
                delay(1.0);
                delayUpdata(1.0);
                return;
            }
            [self requestWithURLStr:@"http://iosapi.itcast.cn/doctor/searchCI3List.json.php" parameters:@{@"page":num,@"page_size":@15,@"ci1_id":self.ID,@"keyword":@""}];
        }];
        footer.refreshingTitleHidden = YES;
        self.tabelView.mj_footer = footer;
    }
}

-(void)viewDidDisappear:(BOOL)animated {
    i = 1;j = 1;
}
@end
